<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="700px"
    @close="resetForm"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <!-- 作业状态提示 -->
      <div v-if="isEdit && homework" class="status-notice">
        <el-alert
          :title="statusNotice.title"
          :type="statusNotice.type"
          :description="statusNotice.description"
          :closable="false"
          show-icon
        />
      </div>

      <el-form-item label="作业标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="如果留空，将使用默认标题"
          :disabled="isReadOnly"
        />
        <div class="form-tip">默认标题：{{ defaultTitle }}</div>
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="选择开始时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled="isEdit && !canEditBasicInfo"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="选择结束时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled="isEdit && !canEditBasicInfo"
        />
      </el-form-item>

      <el-form-item label="作业明细">
        <div class="homework-details">
          <div
            v-for="(detail, index) in form.details"
            :key="index"
            class="detail-item"
            :class="{ 'detail-completed': detail.isCompleted }"
          >
            <div class="detail-status" v-if="detail.isCompleted">
              <el-icon><Check /></el-icon>
              <span>已完成</span>
            </div>
            <el-input
              v-model="detail.content"
              placeholder="输入作业内容"
              style="flex: 1"
              :disabled="detail.isCompleted || isReadOnly"
            />
            <el-select
              v-model="detail.isRequired"
              style="width: 120px; margin-left: 10px"
              :disabled="detail.isCompleted || isReadOnly"
            >
              <el-option label="必须完成" :value="true" />
              <el-option label="非必须" :value="false" />
            </el-select>
            <el-button
              type="danger"
              size="small"
              @click="removeDetail(index)"
              style="margin-left: 10px"
              :disabled="detail.isCompleted || isReadOnly || !canRemoveDetail"
            >
              删除
            </el-button>
          </div>
          <el-button
            type="primary"
            size="small"
            @click="addDetail"
            style="margin-top: 10px"
            :disabled="!canAddDetail"
            v-if="!isReadOnly"
          >
            添加作业项
          </el-button>
        </div>
        <div class="form-tip">
          <el-alert
            title="说明"
            type="info"
            :closable="false"
            style="margin-top: 10px"
          >
            <template #default>
              <div>
                • <strong>必须完成</strong>：完成这些作业即视为今日作业完成<br>
                • <strong>非必须</strong>：可选完成的项目，不会影响作业完成状态<br>
                • 系统会自动添加日常作业模板中的项目
              </div>
            </template>
          </el-alert>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          :disabled="isReadOnly"
        >
          {{ submitButtonText }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { useHomeworkStore } from '@/store/homework'
import dayjs from 'dayjs'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  homework: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const homeworkStore = useHomeworkStore()

const formRef = ref()
const loading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.homework)

// 作业状态相关的计算属性
const homeworkStatus = computed(() => props.homework?.status || 0)
const isReadOnly = computed(() => homeworkStatus.value === 2) // 已完成：只读
const canEditBasicInfo = computed(() => homeworkStatus.value === 0) // 未开始：可编辑基本信息
const canAddDetail = computed(() => homeworkStatus.value !== 2) // 未完成：可添加作业项
const canRemoveDetail = computed(() => homeworkStatus.value !== 2) // 未完成：可删除作业项

// 对话框标题
const dialogTitle = computed(() => {
  if (!isEdit.value) return '添加作业'
  if (homeworkStatus.value === 0) return '编辑作业（未开始）'
  if (homeworkStatus.value === 1) return '编辑作业（进行中）'
  if (homeworkStatus.value === 2) return '查看作业（已完成）'
  return '编辑作业'
})

// 提交按钮文字
const submitButtonText = computed(() => {
  if (isReadOnly.value) return '只读模式'
  if (isEdit.value) return '更新'
  return '创建'
})

// 状态提示信息
const statusNotice = computed(() => {
  switch (homeworkStatus.value) {
    case 0:
      return {
        title: '作业未开始',
        type: 'info',
        description: '可以完全编辑作业的所有内容，包括基本信息和作业项目。'
      }
    case 1:
      return {
        title: '作业进行中',
        type: 'warning',
        description: '可以添加新的作业项和修改未完成的项目。已完成的作业项不能修改或删除。'
      }
    case 2:
      return {
        title: '作业已完成',
        type: 'success',
        description: '作业已完成，当前为只读模式，不能进行任何修改。'
      }
    default:
      return {
        title: '',
        type: 'info',
        description: ''
      }
  }
})

const form = ref({
  title: '',
  startTime: null,
  endTime: null,
  details: [{ content: '', isRequired: true }]
})

const defaultTitle = computed(() => {
  return dayjs().format('YYYY-MM-DD') + '家庭作业'
})

const rules = {
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && form.value.startTime && value <= form.value.startTime) {
          callback(new Error('结束时间必须大于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const addDetail = () => {
  form.value.details.push({ content: '', isRequired: true })
}

const removeDetail = (index) => {
  if (form.value.details.length > 1) {
    form.value.details.splice(index, 1)
  }
}

const resetForm = () => {
  form.value = {
    title: '',
    startTime: null,
    endTime: null,
    details: [{ content: '', isRequired: true }]
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证作业明细
    const validDetails = form.value.details.filter(detail => detail.content.trim())
    if (validDetails.length === 0) {
      ElMessage.error('请至少添加一个作业项')
      return
    }

    loading.value = true

    const submitData = {
      ...form.value,
      title: form.value.title.trim() || defaultTitle.value,
      details: validDetails,
      studentId: 1 // 默认学生ID，实际应用中应该从状态中获取
    }

    // 确保时间格式正确
    console.log('提交数据:', submitData)
    console.log('开始时间:', submitData.startTime)
    console.log('结束时间:', submitData.endTime)

    let response
    if (isEdit.value) {
      response = await homeworkStore.updateHomework(props.homework.id, submitData)
    } else {
      response = await homeworkStore.createHomework(submitData)
    }

    ElMessage.success(isEdit.value ? '作业更新成功' : '作业创建成功')
    visible.value = false
    emit('success')
  } catch (error) {
    console.error('操作失败:', error)
    if (error.message && error.message.includes('冲突')) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 如果是编辑模式，加载作业数据
watch(() => props.homework, (homework) => {
  if (homework) {
    form.value = {
      title: homework.title,
      startTime: homework.startTime,
      endTime: homework.endTime,
      details: homework.details ? [...homework.details] : [{ content: '', isRequired: true }]
    }
  }
}, { immediate: true })
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.homework-details {
  width: 100%;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

/* 状态相关样式 */
.status-notice {
  margin-bottom: 20px;
}

.detail-item {
  position: relative;
}

.detail-completed {
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 4px;
  padding: 8px;
}

.detail-status {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #67c23a;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  display: flex;
  align-items: center;
  gap: 2px;
  z-index: 1;
}

.detail-status .el-icon {
  font-size: 10px;
}

/* 只读模式的样式 */
.is-disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>